package com.billing.web.controller.archives;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.ObjectUtils.Null;
import org.apache.ibatis.javassist.expr.NewArray;
import org.apache.jasper.tagplugins.jstl.core.ForEach;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.billing.config.ServiceConfig;
import com.billing.model.entity.TDept;
import com.billing.model.entity.TOrganization;
import com.billing.model.entity.TUser;
import com.billing.model.entity.TUserBuffer;
import com.billing.model.entity.TUserEducation;
import com.billing.model.entity.TUserEducationBuffer;
import com.billing.model.entity.TUserEmergencycontact;
import com.billing.model.entity.TUserEmergencycontactBuffer;
import com.billing.model.entity.TUserExport;
import com.billing.model.entity.TUserList;
import com.billing.model.entity.TUserPay;
import com.billing.model.entity.TUserPrivate;
import com.billing.model.entity.TUserPrivateBuffer;
import com.billing.model.entity.TUserScan;
import com.billing.model.entity.TUserScanBuffer;
import com.billing.model.entity.TUserWorkexperience;
import com.billing.model.entity.TUserWorkexperienceBuffer;
import com.billing.model.entity.UserExamine;
import com.billing.model.entity.UserScanExamine;
import com.billing.service.AttendanceService;
import com.billing.service.DeptService;
import com.billing.service.OrganizationService;
import com.billing.service.SchedulingService;
import com.billing.service.UserBufferService;
import com.billing.service.UserEducationBufferService;
import com.billing.service.UserEducationService;
import com.billing.service.UserEmergencycontactBufferService;
import com.billing.service.UserEmergencycontactService;
import com.billing.service.UserPayService;
import com.billing.service.UserPrivateBufferService;
import com.billing.service.UserPrivateService;
import com.billing.service.UserScanBufferService;
import com.billing.service.UserScanService;
import com.billing.service.UserService;
import com.billing.service.UserWorkexperienceBufferService;
import com.billing.service.UserWorkexperienceService;
import com.billing.service.impl.UserWorkexperienceServiceImpl;
import com.billing.utils.BankCardPicApiUtil;
import com.billing.utils.DateUtil;
import com.billing.utils.ExcelUtil;
import com.billing.utils.IdIdentificationApiUtil;
import com.billing.utils.MD5Util;

@RequestMapping(value="/user")
@Controller
public class UserController {
	@Resource
	private AttendanceService attendanceService;
	@Resource
	private UserService userService;
	@Resource
	private UserBufferService userCopyService;
	@Resource
	private UserScanService userScanService;
	@Resource
	private UserScanBufferService userScanCopyService;
	@Resource
	private UserEducationService userEducationService;
	@Resource
	private UserEducationBufferService userEducationCopyService;
	@Resource
	private UserEmergencycontactService userEmergencycontactService;
	@Resource
	private UserEmergencycontactBufferService userEmergencycontactCopyService;
	@Resource
	private UserWorkexperienceService userWorkexperienceService;
	@Resource
	private UserWorkexperienceBufferService userWorkexperienceCopyService;
	@Resource
	private UserPrivateService userPrivateService;
	@Resource
	private UserPrivateBufferService userPrivateCopyService;
	@Resource
	private DeptService deptService;
	@Resource
	private UserPayService userPayService;
	@Resource
	private SchedulingService schedulingService;
	@Resource
	private OrganizationService organizationService;
	SimpleDateFormat mdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	SimpleDateFormat formatr = new SimpleDateFormat("yyyyMMdd");
	SimpleDateFormat formatym = new SimpleDateFormat("yyyy-MM");
	
	/**
	 * 获取档案列表信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public String index(HttpServletRequest request, Model model){
		String name = request.getParameter("name");
		String dept = request.getParameter("dept");
		String jobnumber = request.getParameter("jobnumber");
		String selectbut=request.getParameter("selectbut");
		int pageSize = 10;
		String fromDateStr = request.getParameter("fromDate") == null ? "" : request.getParameter("fromDate");//开始时间;
		String endDateStr = request.getParameter("endDate") == null ? "" : request.getParameter("endDate");//结束时间;
		try {
			if (dept!=null&&dept.length() > 0) {
				dept = URLDecoder.decode(URLDecoder.decode(dept, "UTF-8"),"UTF-8");
			}
			if (name!=null&&name.length() > 0) {
				name = URLDecoder.decode(URLDecoder.decode(name, "UTF-8"),"UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
		} 
		List<TDept> deptlist=deptService.getTDeptlist();
		request.setAttribute("fromDate", fromDateStr);
		request.setAttribute("endDate", endDateStr);
		request.setAttribute("name", name);
		request.setAttribute("dept", dept);
		request.setAttribute("jobnumber", jobnumber);
		request.setAttribute("deptlist", deptlist);
		Long starttime = 0l;
		Long endtime = 0l;
		Date startDate = null;
		Date endDate = null;
		try {
			fromDateStr=fromDateStr+" 00:00:00";
			endDateStr=endDateStr+" 23:59:59";
			startDate = mdf.parse(fromDateStr);
			endDate = mdf.parse(endDateStr);
			starttime=startDate.getTime();
			endtime=endDate.getTime();
		} catch (Exception e) {
		}
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		int totalNum = userService.selectTUserNum(name, dept, starttime, endtime, jobnumber,organizationid);
		int totalPage = totalNum / pageSize;
		if (totalNum % pageSize != 0) {
			totalPage++;	
		}
		totalPage = totalPage <= 0 ? 1 : totalPage;
		currentPage = currentPage > totalPage ? totalPage : currentPage;
		List<TUser> list=userService.selectTUserList(name, dept, starttime, endtime,jobnumber, organizationid,(currentPage - 1) * pageSize, pageSize);
		
		request.setAttribute("totalNum", totalNum);
		request.setAttribute("list", list);
		request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalNum", totalNum);
        request.setAttribute("totalPage", totalPage);
		return "archives/index"; 
	}
	 
	/*******/
	//导出人员档案信息
	@RequestMapping("exportUser")  
    public void exportInof(HttpServletRequest request,HttpServletResponse response) throws Exception{  
		Date day=new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy");
        response.setContentType("application/vnd.ms-excel");  
        response.setHeader("Content-Disposition", "attachment; filename=user.xls");  
        String filename="人员档案.xls";
	    filename = new String(filename.getBytes(), "ISO-8859-1");
	    response.setHeader("Content-Disposition", "attachment; filename="+filename); 
        OutputStream out = response.getOutputStream();  
        String name = new String(request.getParameter("name").getBytes("iso8859-1"), "UTF-8");
		String dept = request.getParameter("dept");
		String jobnumber = request.getParameter("jobnumber");
		String fromDateStr = request.getParameter("fromDate");
		String endDateStr = request.getParameter("endDate");
		try {
			if (dept!=null&&dept.length() > 0) {
				dept = URLDecoder.decode(URLDecoder.decode(dept, "UTF-8"),"UTF-8");
			}
			if (name!=null&&name.length() > 0) {
				name = URLDecoder.decode(URLDecoder.decode(name, "UTF-8"),"UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
		}
		request.setAttribute("fromDate", fromDateStr);
		request.setAttribute("endDate", endDateStr);
		request.setAttribute("name", name);
		request.setAttribute("dept", dept);
		request.setAttribute("jobnumber", jobnumber);
		Long starttime = 0l;
		Long endtime = 0l;
		Date startDate = null;
		Date endDate = null;
		try {
			fromDateStr+=fromDateStr+" 00:00:00";
			endDateStr+=endDateStr+" 23:59:59";
			startDate = mdf.parse(fromDateStr);
			endDate = mdf.parse(endDateStr);
			starttime=startDate.getTime();
			endtime=endDate.getTime();
		} catch (Exception e) {
		}
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		int totalNum = userService.selectTUserNum(name, dept, starttime, endtime, jobnumber,organizationid);
		
		
		int pageSize = totalNum;
		int totalPage = totalNum / pageSize;
		if (totalNum % pageSize != 0) {
			totalPage++;	
		}
		totalPage = totalPage <= 0 ? 1 : totalPage;
		currentPage = currentPage > totalPage ? totalPage : currentPage;
		List<TUser> list=userService.selectTUserList(name, dept, starttime, endtime,jobnumber,organizationid, (currentPage - 1) * pageSize, pageSize); 
		
		List<TUserExport> replist=new ArrayList<TUserExport>();
		
		for (TUser pay : list) {
			TUserExport rep=new TUserExport();
			rep.setJobnumber(pay.getJobnumber());
			rep.setName(pay.getName());
			rep.setIdcard(pay.getIdcard());
			String sex = null;
			if(pay.getSex() == null){sex = "";}else if(pay.getSex() == 1){sex = "男";}else{sex = "女";}
			rep.setSex(sex);
			rep.setDepartment(pay.getDept().getName());
			rep.setPostname(pay.getRole().getName());
			rep.setPostgrade("员工");
			rep.setEntrytime(pay.getEntrytimeString());
			rep.setType("合同制员工");
			rep.setDatebirth(pay.getDatebirthString());
			rep.setHighesteducation(pay.getHighesteducation());
			String maritalstatus = null;
			if(pay.getMaritalstatus() == null){maritalstatus="";}else if(pay.getMaritalstatus() == 1){
				maritalstatus = "是";
			}else if(pay.getMaritalstatus() == 2){maritalstatus = "否";}
			rep.setMaritalstatus(maritalstatus);
			rep.setOrigin(pay.getOrigin());
			rep.setAge("");
			rep.setNation(pay.getNation());
			String status = null;
			if(pay.getStatus() == null){status="";}else if(pay.getStatus() == 0){
				status = "试用";
			}else if(pay.getStatus() == 1){status = "正式";}
			rep.setStatus(status);
			rep.setHouseholdTye("");
			rep.setBirthplace(pay.getBirthplace());
			rep.setEntrancetime("");
			rep.setGraduationtime(pay.getEdu().getGraduationtimeString());
			rep.setSchool(pay.getEdu().getUniversitie());
			rep.setProfessional(pay.getProfessional());
			String nature = null;
			if(pay.getNature() == null){nature="";}else if(pay.getNature() == 3){
				nature = "是";
			}else{nature = "否";}
			rep.setNature(nature);
			rep.setHourlywage(pay.getHourlywage());
			rep.setWorkplaceId(pay.getWorkplaceId());
			rep.setSendaddress(pay.getSendaddress());
			rep.setMobile(pay.getMobile());
			rep.setMail(pay.getMail());
			replist.add(rep);
		}
		
		ExcelUtil<TUserExport> t=new ExcelUtil<TUserExport>();
		String [] headers={"工号","姓名","身份证号","性别","部门名称","岗位名称","岗位等级","到职日期","人员类别","出生日期","最高学历","婚姻状况","员工籍贯"
				,"年龄","民族","是否转正","员工户口性质","员工户口所在地","入学日期","毕业日期","学校","所学专业","是否实习生"
				,"合同工资","合同主体单位","派遣至单位","手机","邮箱"};
		t.exportExcel("人员档案列表", headers, replist, out, "yyyy-MM-dd HH:mm:ss");
        
	}
		
	//导入页面
		@RequestMapping(value="/importpage",method=RequestMethod.GET)
		public String importpage(HttpServletRequest request, Model model){
			return "archives/importBill";
		}
		
		
		
		//导入人员档案数据
		@RequestMapping(value = "improtExcel", method = RequestMethod.POST)
	    public String improtExcel(HttpServletRequest request, @RequestParam(value="uploadFile") MultipartFile file) {
	        int organizationId=(int) request.getSession().getAttribute("organizationid");
	        try {
	            List<Map<String, Object>> list = ImportExcelUntil.importExcel(file, new TUserList());
	            
	            System.out.println(list.size());
	            
	            for(Map m : list){
	            	TUserList tus = new TUserList();
	            	 
	                tus.setOrganization_id(organizationId);
	                tus.setName(m.get("name").toString().equals("0.0")? "" : m.get("name").toString());
	                String mobile_ = m.get("mobile").toString();//手机号码
	                TUser phones = null;
					try {
						phones = userService.getPhoneNumber(mobile_);
					} catch (Exception e2) {
						e2.printStackTrace();
					}
	                int i = 0;
	                if(phones != null){
	                String mobile = phones.getMobile();
	                String archiving_time = phones.getArchiving_time();
	                boolean da = false;
					if(mobile.equals(mobile_)){
						if(archiving_time.equals("0")){
							request.setAttribute("msg", "号码为："+mobile_+"已有账号注册！！！");
				            return "archives/importBill";
						}else{
							if(phones.getOrganizationId() == organizationId){
								da = true;
							}
						}
					}
					
					if(da){
						userService.updatearchivingtime(mobile_);
						i=1;
					}
	                }
	                tus.setMobile(mobile_);
	                String idcard_ = m.get("idcard").toString();
	                /*if(!idcard_.equals("0.0")&&idcard_!=null&&!idcard_.equals("")){
	                	idcard_ = idcard_.substring(0, idcard_.length()-2);
	                }else{idcard_="";}*/
	                tus.setIdcard(idcard_);
	                String sex_ = m.get("sex").toString();
	                int sex = 0;
	                if(sex_ == ""){
	                	sex=1;
	                }else{
	                	if(sex_.equals("男")){
	                		sex = 1;
	                	}else if(sex_.equals("女")){sex = 2;}}
	                tus.setSex(sex);
	                //tus.setDepartment(m.get("department").toString());
	                //tus.setPostname(m.get("postname").toString());
	                //tus.setPostgrade(m.get("postgrade").toString());
	                String entrytime = m.get("entrytime").toString().equals("0.0")? "" : m.get("entrytime").toString();
	                Long entrytimeLong = null;
	                if(entrytime!=""){
		        		try {
							entrytimeLong = formatr.parse(entrytime).getTime();
						} catch (Exception e) {
							e.printStackTrace();
						}
	                }
	                tus.setEntrytime(entrytimeLong);
	                //tus.setType(m.get("type").toString());
	                String datebirth = m.get("datebirth").toString().equals("0.0")? "" : m.get("datebirth").toString();
	                Long datebirthLong = null;
	                if(datebirth!=""){
		        			try {
								datebirthLong = formatr.parse(datebirth).getTime();
							} catch (Exception e) {
								e.printStackTrace();
							}
	                }
	                tus.setDatebirth(datebirthLong);
	                tus.setHighesteducation(m.get("highesteducation").toString());
	                String maritalstatus_ = m.get("maritalstatus").toString();
	                int maritalstatus = 0;
	                if(maritalstatus_==null){
	                	maritalstatus=2;
	                }else{
	                	if(maritalstatus_.equals("是")){
	                		maritalstatus = 1;
	                	}else if(maritalstatus_.equals("否")){
	                		maritalstatus = 2;
	                	}
	                }
	                tus.setMaritalstatus(maritalstatus);
	                tus.setOrigin(m.get("origin").toString());
	                //tus.setAge(m.get("age").toString());
	                tus.setNation(m.get("nation").toString());
	                String status_ = m.get("status").toString();
	                int status = 0;
	                if(status_==null){
	                	status=1;
	                }else{
	                	if(status_.equals("是")){
	                		status = 1;
	                	}else if(status_.equals("否")){
	                		status = 0;
	                	}
	                }
	                tus.setStatus(status);
	                //tus.setHouseholdTye(m.get("householdTye").toString());
	                tus.setBirthplace(m.get("birthplace").toString());
	                //tus.setEntrancetime(m.get("entrancetime").toString());
	                //tus.setGraduationtime(m.get("graduationtime").toString());
	                //tus.setSchool(m.get("school").toString());
	                tus.setProfessional(m.get("professional").toString());
	                String nature_ = m.get("nature").toString();
	                int nature = 0;
	                if(nature_==null){
	                	nature = 1;
	                }else{
	                	if(nature_.equals("是")){
	                		nature = 3;
	                	}else if(nature_.equals("否")){
	                		nature = 1;
	                	}
	                }
	                tus.setNature(nature);
	                String hourlywage = m.get("hourlywage").toString();
	                double hourlywage_ = 0;
	                if(!hourlywage.equals("0.0")&&hourlywage!=null&&!hourlywage.equals("")){
	                	hourlywage_=Double.parseDouble(hourlywage);
	                }else{hourlywage_ = hourlywage_;}
	                tus.setHourlywage(hourlywage_);
	                //tus.setWorkplaceId(1);
	                tus.setSendaddress(m.get("sendaddress").toString());
	                
	                
	                
	                tus.setMail(m.get("mail").toString().equals("0.0")? "" : m.get("mail").toString());
	                long date = new Date().getTime();  
	                tus.setCreatetime(date);
	                long time=System.currentTimeMillis();
	                int organizationid=(int) request.getSession().getAttribute("organizationid");
	        		TOrganization ion=organizationService.getTOrganizationByid(organizationid);
	                String format=DateUtil.getStringFormat(time, "yyyyMMdd")+"00000";
	        		if(ion!=null){
	        			String number=String.valueOf(ion.getNumber());
	        			int length=number.length();
	        			format=format.substring(0, format.length()-length)+number;
	        		}
	            	tus.setJobnumber(format);
	            	
	            	TOrganization ions=organizationService.getTOrganizationByid(organizationid);
	            	ions.setNumber(ions.getNumber()+1);
	                //初始化登陆名与密码
	                String password="";
	                try {
	                    password=MD5Util.md5Encode("123456");
	                } catch (Exception e1) {
	                    e1.printStackTrace();
	                }
	            	tus.setLoginname(mobile_);
	                tus.setPassword(password);
	                String language_="";
	        		tus.setLanguage(language_);
	        		
	        		if (m.get("datebirth").toString().equals("0.0")||m.get("name").toString().equals("0.0"))
	        	    {
	        			break;
	        	    }
	        		
	            	if(i == 0){
	            		userService.insertTUserList(tus);
	            	}
	            	organizationService.updateTOrganization(ions);
	            	
	            }
	            
	            
	        } catch (Exception e) {
	            e.printStackTrace();
	            request.setAttribute("msg", "导入格式有误已中断!");
	            return "archives/importBill";
	        }
	        request.setAttribute("msg", "导入成功!");
	        return "archives/importBill";
	    }
		
		/********/
	
	
	
		
	@RequestMapping(value="/updateJobStatus",method=RequestMethod.POST)
	@ResponseBody
	public String updateJobStatus(HttpServletRequest request,Model model){
		String id = request.getParameter("id");
		TUser user = userService.getTUserById(id);
		System.out.println(id+"编号");
		//离职操作
		userService.updateJobStatus(id, "2");
		long atime=System.currentTimeMillis();
		userService.updateArchivingTime(id,atime);
		//在职操作
		Long time = user.getArchivingTime();
		System.out.println(time+"啦啦啦啦啦");
		if (user.getArchivingTime() != 0) {
			userService.updateJobStatus(id, "1");
			userService.updateArchivingTime(id, 0);
		}
		return "ok";
	}
	/**
	 * 修改个人档案记录
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/update",method=RequestMethod.GET)
	public String update(HttpServletRequest request, Model model){
		String id = request.getParameter("id");
		TUser user=userService.selectTUserId(id);
		request.setAttribute("user", user);
		return "archives/updateUser";
	}
	/**
	 * 增加用户页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/addUsermain",method=RequestMethod.GET)
	public String addUsermain(HttpServletRequest request, Model model){
		long time=System.currentTimeMillis();
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		TOrganization ion=organizationService.getTOrganizationByid(organizationid);
		String format=DateUtil.getStringFormat(time, "yyyyMMdd")+"00000";
		if(ion!=null){
			String number=String.valueOf(ion.getNumber());
			int length=number.length();
			format=format.substring(0, format.length()-length)+number;
		}
		request.setAttribute("jobnumber", format);
		return "archives/addUser";
	}
	
	/**
	 * 修改用户页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/updateUsermain",method=RequestMethod.GET)
	public String updateUsermain(HttpServletRequest request, Model model){
		String id=request.getParameter("id");
		String type=request.getParameter("type");
		TUser user=userService.selectTUserId(id);
		request.setAttribute("user", user);
        Long datebirth=user.getDatebirth();
        for (TUserEducation education : user.getEducationlist()) {
			if(education.getGraduationtime() != null){
				education.setGraduationtimeString(format.format(education.getGraduationtime()));
			}
		}
        String[] languageArr = user.getLanguage().split(",");
        request.setAttribute("languageArr", languageArr);
        if(datebirth!=null){
            request.setAttribute("datebirth", format.format(datebirth));
        }
        String result="";
        if("select".equals(type)){
        	result="archives/lookUser";
        }else if("update".equals(type)){
        	result="archives/updateUser";
        }
        return result;
	}
	/**
	 * 查询用户资料比对页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/examineUsermain",method=RequestMethod.GET)
	public String examineUsermain(HttpServletRequest request, Model model){
		String id=request.getParameter("id");
		TUser user=userService.selectTUserId(id);
		TUserBuffer userCopy = userCopyService.selectTUserId(id);
		
		TUserPrivate userPrivate = null;
		TUserPrivateBuffer privateCopy = null;
		List<TUserEducation> educations = new ArrayList<>();
		List<TUserEducationBuffer> educationCopies = new ArrayList<>();
		List<TUserEmergencycontact> userEmergencycontacts = new ArrayList<>();
		List<TUserEmergencycontactBuffer> emergencycontactCopies = new ArrayList<>();
		List<TUserWorkexperience> userWorkexperiences = new ArrayList<>();
		List<TUserWorkexperienceBuffer> userWorkexperienceCopies = new ArrayList<>();
		
		List<UserScanExamine> userScanExamines = new ArrayList<>();
		
		List<UserExamine> list = new ArrayList<>();
		UserExamine examine = null;
		//基本资料比对
		if(!(user.getName() != null ? user.getName():"").equals((userCopy.getName() != null ? userCopy.getName():""))){
			examine = new UserExamine();
			examine.setViewName("姓名");
			examine.setOldData(user.getName());
			examine.setNewData(userCopy.getName());
			list.add(examine);
		}   
		if(!(user.getSex() != null ? user.getSex():"").equals((userCopy.getSex() != null ? userCopy.getSex():""))){
			examine = new UserExamine();
			examine.setViewName("性别");
			if(user.getSex() == 1){
				examine.setOldData("男");
			}else if (user.getSex() == 2) {
				examine.setOldData("女");
			}
			if(userCopy.getSex() == 1){
				examine.setNewData("男");
			}else if (userCopy.getSex() == 2) {
				examine.setNewData("女");
			}
			list.add(examine);
		}
		if(!(user.getDatebirth() != null ? user.getDatebirth():"").equals((userCopy.getDatebirth() != null ? userCopy.getDatebirth():""))){
			examine = new UserExamine();
			examine.setViewName("出生日期");
			Long datebirth=user.getDatebirth();
			Long datebirthCopy=userCopy.getDatebirth();
			if(datebirth!=null){
				examine.setOldData(format.format(datebirth));
			}
			if(datebirthCopy!=null){
				examine.setNewData(format.format(datebirthCopy));
			}
			list.add(examine);
		}
		if(!(user.getOrigin() != null ? user.getOrigin():"").equals((userCopy.getOrigin() != null ? userCopy.getOrigin():""))){
			examine = new UserExamine();
			examine.setViewName("籍贯");
			examine.setOldData(user.getOrigin());
			examine.setNewData(userCopy.getOrigin());
			list.add(examine);
		}
		if(!(user.getNation() != null ? user.getNation():"").equals((userCopy.getNation() != null ? userCopy.getNation():""))){
			examine = new UserExamine();
			examine.setViewName("民族");
			examine.setOldData(user.getNation());
			examine.setNewData(userCopy.getNation());
			list.add(examine);
		}
		if(!(user.getPoliticalstatus() != null ? user.getPoliticalstatus():"").equals((userCopy.getPoliticalstatus() != null ? userCopy.getPoliticalstatus():""))){
			examine = new UserExamine();
			examine.setViewName("政治面貌");
			examine.setOldData(user.getPoliticalstatus());
			examine.setNewData(userCopy.getPoliticalstatus());
			list.add(examine);
		}
		if(!(user.getLanguage() != null ? user.getLanguage():"").equals((userCopy.getLanguage() != null ? userCopy.getLanguage():""))){
			examine = new UserExamine();
			examine.setViewName("语言");
			examine.setOldData(user.getLanguage());
			examine.setNewData(userCopy.getLanguage());
			list.add(examine);
		}
		if(!(user.getSpeciality() != null ? user.getSpeciality():"").equals((userCopy.getSpeciality() != null ? userCopy.getSpeciality():""))){
			examine = new UserExamine();
			examine.setViewName("特长");
			examine.setOldData(user.getSpeciality());
			examine.setNewData(userCopy.getSpeciality());
			list.add(examine);
		}
		if(!(user.getHighesteducation() != null ? user.getHighesteducation():"").equals((userCopy.getHighesteducation() != null ? userCopy.getHighesteducation():""))){
			examine = new UserExamine();
			examine.setViewName("最高学历");
			examine.setOldData(user.getHighesteducation());
			examine.setNewData(userCopy.getHighesteducation());
			list.add(examine);
		}
		if(!(user.getProfessional() != null ? user.getProfessional():"").equals((userCopy.getProfessional() != null ? userCopy.getProfessional():""))){
			examine = new UserExamine();
			examine.setViewName("专业");
			examine.setOldData(user.getProfessional());
			examine.setNewData(userCopy.getProfessional());
			list.add(examine);
		}
		if(!(user.getIdcard() != null ? user.getIdcard():"").equals((userCopy.getIdcard() != null ? userCopy.getIdcard():""))){
			examine = new UserExamine();
			examine.setViewName("身份证号码");
			examine.setOldData(user.getIdcard());
			examine.setNewData(userCopy.getIdcard());
			list.add(examine);
		}
		if(!(user.getMaritalstatus() != null ? user.getMaritalstatus():"").equals((userCopy.getMaritalstatus() != null ? userCopy.getMaritalstatus():""))){
			examine = new UserExamine();
			examine.setViewName("婚姻状态");
			if(user.getMaritalstatus() == 1){
				examine.setOldData("已婚");
			}else if(user.getMaritalstatus() == 2){
				examine.setOldData("未婚");
			}
			if(userCopy.getMaritalstatus() == 1){
				examine.setNewData("已婚");
			}else if(userCopy.getMaritalstatus() == 2){
				examine.setNewData("未婚");
			}
			list.add(examine);
		}
		if(!(user.getHeight() != null ? user.getHeight():"").equals((userCopy.getHeight() != null ? userCopy.getHeight():""))){
			examine = new UserExamine();
			examine.setViewName("身高");
			examine.setOldData(user.getHeight());
			examine.setNewData(userCopy.getHeight());
			list.add(examine);
		}
		if(!(user.getWeight() != null ? user.getWeight():"").equals((userCopy.getWeight() != null ? userCopy.getWeight():""))){
			examine = new UserExamine();
			examine.setViewName("体重");
			examine.setOldData(user.getWeight());
			examine.setNewData(userCopy.getWeight());
			list.add(examine);
		}
		if(!(user.getVision() != null ? user.getVision():"").equals((userCopy.getVision() != null ? userCopy.getVision():""))){
			examine = new UserExamine();
			examine.setViewName("视力");
			examine.setOldData(user.getVision());
			examine.setNewData(userCopy.getVision());
			list.add(examine);
		}
		if(!(user.getMobile() != null ? user.getMobile():"").equals((userCopy.getMobile() != null ? userCopy.getMobile():""))){
			examine = new UserExamine();
			examine.setViewName("手机");
			examine.setOldData(user.getMobile());
			examine.setNewData(userCopy.getMobile());
			list.add(examine);
		}
		if(!(user.getQq() != null ? user.getQq():"").equals((userCopy.getQq() != null ? userCopy.getQq():""))){
			examine = new UserExamine();
			examine.setViewName("QQ");
			examine.setOldData(user.getQq());
			examine.setNewData(userCopy.getQq());
			list.add(examine);
		}
		if(!(user.getMail() != null ? user.getMail():"").equals((userCopy.getMail() != null ? userCopy.getMail():""))){
			examine = new UserExamine();
			examine.setViewName("邮件地址");
			examine.setOldData(user.getMail());
			examine.setNewData(userCopy.getMail());
			list.add(examine);
		}
		if(!(user.getWeixinid() != null ? user.getWeixinid():"").equals((userCopy.getWeixinid() != null ? userCopy.getWeixinid():""))){
			examine = new UserExamine();
			examine.setViewName("微信号");
			examine.setOldData(user.getWeixinid());
			examine.setNewData(userCopy.getWeixinid());
			list.add(examine);
		}
		if(!(user.getBirthplace() != null ? user.getBirthplace():"").equals((userCopy.getBirthplace() != null ? userCopy.getBirthplace():""))){
			examine = new UserExamine();
			examine.setViewName("户口所在地");
			examine.setOldData(user.getBirthplace());
			examine.setNewData(userCopy.getBirthplace());
			list.add(examine);
		}
		if(!(user.getAddress() != null ? user.getAddress():"").equals((userCopy.getAddress() != null ? userCopy.getAddress():""))){
			examine = new UserExamine();
			examine.setViewName("现居住地址");
			examine.setOldData(user.getAddress());
			examine.setNewData(userCopy.getAddress());
			list.add(examine);
		}
		if(!(user.getReferee() != null ? user.getReferee():"").equals((userCopy.getReferee() != null ? userCopy.getReferee():""))){
			examine = new UserExamine();
			examine.setViewName("推荐人");
			examine.setOldData(user.getReferee());
			examine.setNewData(userCopy.getReferee());
			list.add(examine);
		}
		if(!(user.getIfsend() != null ? user.getIfsend():"").equals((userCopy.getIfsend() != null ? userCopy.getIfsend():""))){
			examine = new UserExamine();
			examine.setViewName("能否接受外派");
			if(user.getIfsend() == 1){
				examine.setOldData("能");
			}else if(user.getIfsend() == 2){
				examine.setOldData("否");
			}
			if(userCopy.getIfsend() == 1){
				examine.setNewData("能");
			}else if(userCopy.getIfsend() == 2){
				examine.setNewData("否");
			}
			list.add(examine);
		}
		if(!(user.getSendaddress() != null ? user.getSendaddress():"").equals((userCopy.getSendaddress() != null ? userCopy.getSendaddress():""))){
			examine = new UserExamine();
			examine.setViewName("外派地区");
			examine.setOldData(user.getSendaddress());
			examine.setNewData(userCopy.getSendaddress());
			list.add(examine);
		}
		//私密信息比对
		if(ComparisonPrivate(user.getUserPrivate(), userCopy.getUserPrivate())){
			userPrivate = user.getUserPrivate();
			privateCopy = userCopy.getUserPrivate();
		}
		//学历信息比对
		if(ComparisonEducations(user.getEducationlist(), userCopy.getEducationlist())){
			educations = user.getEducationlist();
			educationCopies = userCopy.getEducationlist();
		}
		//紧急联系人信息比对
		if(ComparisonEmergencycontact(user.getUserEmergencycontactlist(), userCopy.getUserEmergencycontactlist())){
			userEmergencycontacts = user.getUserEmergencycontactlist();
			emergencycontactCopies = userCopy.getUserEmergencycontactlist();
		}
		//工作经验信息比对
		if(ComparisonWorkexperience(user.getUserWorkexperiencelist(), userCopy.getUserWorkexperiencelist())){
			userWorkexperiences = user.getUserWorkexperiencelist();
			userWorkexperienceCopies = userCopy.getUserWorkexperiencelist();
		}
		//附件信息比对
		if(ComparisonScan(user.getScanlist(), userCopy.getScanlist())){
			for (TUserScan scan : user.getScanlist()) {
				for (TUserScanBuffer scanCopy : userCopy.getScanlist()) {
					if(scan.getType() == scanCopy.getType()){
						if(!scan.getPath().equals(scanCopy.getPath())){
							UserScanExamine scanExamine = new UserScanExamine();
							scanExamine.setOldFilePath(scan.getPath());
							scanExamine.setNewFilePath(scanCopy.getPath());
							if(scan.getType() == 1){
								scanExamine.setScanType("员工登记表");
							}else if (scan.getType() == 2) {
								scanExamine.setScanType("入职简历");
							}else if (scan.getType() == 3) {
								scanExamine.setScanType("入职体检表");
							}else if (scan.getType() == 4) {
								scanExamine.setScanType("身份证");
							}else if (scan.getType() == 5) {
								scanExamine.setScanType("学历");
							}else if (scan.getType() == 6) {
								scanExamine.setScanType("合同");
							}else if (scan.getType() == 7) {
								scanExamine.setScanType("上家公司离职证明");
							}else if (scan.getType() == 8) {
								scanExamine.setScanType("离职证明审批");
							}else if (scan.getType() == 9) {
								scanExamine.setScanType("离职证明");
							}else if (scan.getType() == 10) {
								scanExamine.setScanType("面试记录");
							}else if (scan.getType() == 11) {
								scanExamine.setScanType("银行卡");
							}else if (scan.getType() == 12) {
								scanExamine.setScanType("身份证反面");
							}
							userScanExamines.add(scanExamine);
						}
					}
				}
			}
			
		}
		request.setAttribute("jobnumber", user.getJobnumber());
		request.setAttribute("examineList", list);
		request.setAttribute("userPrivate", userPrivate);
		request.setAttribute("privateCopy", privateCopy);
		request.setAttribute("educations", educations);
		request.setAttribute("educationCopies", educationCopies);
		request.setAttribute("emergencycontacts", userEmergencycontacts);
		request.setAttribute("emergencycontactCopies", emergencycontactCopies);
		request.setAttribute("workexperiences", userWorkexperiences);
		request.setAttribute("workexperienceCopies", userWorkexperienceCopies);
		request.setAttribute("userScanExamines", userScanExamines);
		request.setAttribute("userid", user.getId());
	
		return "archives/examineUser";
	}
	//比对修改用户信息
	@RequestMapping(value ="/examine",method = RequestMethod.POST)
	@ResponseBody
	public String examine(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String userid = request.getParameter("userid");
		TUserBuffer userCopy = userCopyService.selectTUserId(userid);
		//判断手机号码是否可用
		if(userService.userMobileIsExist(userCopy.getMobile(), userCopy.getOrganizationId()+"", userid)){
			return "mobileExist";
		}
		if(userCopy.getIdcard() != null && !userCopy.getIdcard().equals("")){
			//判断身份证号码是否可用
			if(userService.userIdcardIsExist(userCopy.getIdcard(), userCopy.getOrganizationId()+"", userid)){
				return "idcardExist";
			}
		}
		//更新基本信息
		userService.updateByBuffer(userCopy);
		//更新私密信息
		TUserPrivateBuffer privateBuffer = userCopy.getUserPrivate();
		if(userPrivateService.updateByBuffer(privateBuffer) == 0){
			userPrivateService.insertByBuffer(privateBuffer);
		}
		//更新学历信息
		List<TUserEducationBuffer> eduList = userCopy.getEducationlist();
		for (TUserEducationBuffer tUserEducationBuffer : eduList) {
			if(userEducationService.updateByBuffer(tUserEducationBuffer) == 0){
				userEducationService.insertByBuffer(tUserEducationBuffer);
			}
		}
		//更新紧急联系人信息
		List<TUserEmergencycontactBuffer> emeList = userCopy.getUserEmergencycontactlist();
		for (TUserEmergencycontactBuffer tUserEmergencycontactBuffer : emeList) {
			if(userEmergencycontactService.updateByBuffer(tUserEmergencycontactBuffer) == 0){
				userEmergencycontactService.insertByBuffer(tUserEmergencycontactBuffer);
			}
		}
		//更新工作经验信息
		List<TUserWorkexperienceBuffer> worList = userCopy.getUserWorkexperiencelist();
		for (TUserWorkexperienceBuffer tUserWorkexperienceBuffer : worList) {
			if(userWorkexperienceService.updateByBuffer(tUserWorkexperienceBuffer) == 0){
				userWorkexperienceService.insertByBuffer(tUserWorkexperienceBuffer);
			}
		}
		//更新附件信息
		List<TUserScanBuffer> scaList = userCopy.getScanlist();
		for (TUserScanBuffer tUserScanBuffer : scaList) {
			if(userScanService.updateByBuffer(tUserScanBuffer) == 0){
				userScanService.insertByBuffer(tUserScanBuffer);
			}
		}
		//修改用户资料审核状态
		int f = userService.updateExamineStatus(userid, "1");
		if(f == 1){
			return "ok";
		}else {
			return "no";
		}
	}
	/**
	 * 显示图片页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/imgmain",method=RequestMethod.GET)
	public String imgmain(HttpServletRequest request, Model model){
		String path=request.getParameter("path");
		request.setAttribute("path",path);
		return "archives/imgmain";
	}
    @RequestMapping("lookimage")  
    public void lookimage(HttpServletRequest request,HttpServletResponse response) throws Exception{ 
        //图片
    	String path=request.getParameter("path");
        String filepath=ServiceConfig.fileUploadPath +"/"+path.split("upload/")[1];
        File filePic = new File(filepath);
        if(filePic.exists()){
           FileInputStream is = new FileInputStream(filePic);
           int i = is.available(); // 得到文件大小  
           byte data[] = new byte[i];  
           is.read(data); // 读数据  
           is.close();  
           response.setContentType("image/*"); // 设置返回的文件类型  
           OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象  
           toClient.write(data); // 输出数据  
           toClient.close();  
        }
    } 
	//保存用户信息
	@RequestMapping(value ="/save",method = RequestMethod.POST)
	@ResponseBody
	public String save(MultipartFile mfile,
            HttpServletRequest request,HttpServletResponse response) throws IOException{
		String entrytime = request.getParameter("entrytime");
		Long entrytimeLong = null;
		try {
			entrytimeLong = format.parse(entrytime).getTime();
		} catch (ParseException e2) {
			e2.printStackTrace();
		}
		String name = request.getParameter("name");
		String sex = request.getParameter("sex");
		String datebirth = request.getParameter("datebirth");
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		Long date_birth = null;
        if(!"".equals(datebirth)&&datebirth!=null){
            try {
                 date_birth=format.parse(datebirth).getTime();
            } catch (ParseException e1) {
                // TODO 自动生成的 catch 块
                e1.printStackTrace();
            }
        }

        //查询排班信息默认第一条
        if(schedulingService.geTSchedulingsByOrganizationid(organizationid).size() < 1){
        	return "nosche";
        }
        int scheid = schedulingService.geTSchedulingsByOrganizationid(organizationid).get(0).getId();
		
        String origin = request.getParameter("origin");
		String politicalstatus = request.getParameter("politicalstatus");
		String[] lang =request.getParameterValues("language");
		
		String language_="";
		if(lang != null){
			for (int i = 0; i < lang.length; i++) {
				if(i==0){
					language_ = lang[i];
				}else{
					language_ += "," + lang[i];
				}
			}
		}
        String nation=request.getParameter("nation");

		String speciality = request.getParameter("speciality");
		String highesteducation = request.getParameter("highesteducation");
		String professional = request.getParameter("professional");
		String idcard = request.getParameter("idcard");
		String maritalstatus = request.getParameter("maritalstatus");
		int maritalstatus_=0;
		if(!"".equals(maritalstatus)){
			maritalstatus_=Integer.parseInt(maritalstatus);
		}
		String height = request.getParameter("height");
		String weight = request.getParameter("weight");
		String vision = request.getParameter("vision");
		String mobile = request.getParameter("mobile");
		if(mobile == null){
			return "no";
		}else if(mobile.equals("")){
			return "no";
		}
		if(mobile != null && !mobile.equals("")){
			//判断手机号码是否可以注册
			if(userService.userMobileIsExist(mobile,organizationid+"",null)){
				return "mobileExist";
			}
		}
		if(idcard != null && !idcard.equals("")){
			//判断身份证是否可以注册
			if(userService.userIdcardIsExist(idcard, organizationid+"",null)){
				return "idcardExist";
			}
		}
		
		
		String qq = request.getParameter("qq");
		String mail = request.getParameter("mail");
		String weixinid = request.getParameter("weixinid");
		String birthplace = request.getParameter("birthplace");
		String address = request.getParameter("address");
		String referee = request.getParameter("referee");
		String ifsend = request.getParameter("ifsend");
		String sendaddress = request.getParameter("sendaddress");
        String jobnumber=request.getParameter("jobnumber");
        Long createtime=new Date().getTime();

		String img="";
        //初始化登陆名与密码
        String password="";
        try {
            password=MD5Util.md5Encode("123456");
        } catch (Exception e1) {
            // TODO 自动生成的 catch 块
            e1.printStackTrace();
        }

		TUser user=new TUser();
		user.setJobStatus(1);//默认在职 
		user.setEntrytime(entrytimeLong);
		user.setOrganizationId(organizationid);
        user.setPassword(password);
        user.setJobnumber(jobnumber);
        user.setLoginname(mobile);
        user.setSchedulingId(scheid);
        if(nation == null || nation.equals("")){
        	user.setNation("汉族");
        }else {
        	user.setNation(nation);
		}
		user.setName(name);
		user.setSex(Integer.parseInt(sex));
		user.setDatebirth(date_birth);
		user.setOrigin(origin);
		if(politicalstatus == null || politicalstatus.equals("")){
			user.setPoliticalstatus("群众");
		}else {
			user.setPoliticalstatus(politicalstatus);
		}
		user.setLanguage(language_);
		user.setSpeciality(speciality);
		user.setHighesteducation(highesteducation);
		user.setProfessional(professional);
		user.setIdcard(idcard);
		if(maritalstatus_ == 0){
			user.setMaritalstatus(2);
		}else {
			user.setMaritalstatus(maritalstatus_);
		}
		user.setHeight(height);
		user.setWeight(weight);
		user.setVision(vision);
		user.setMobile(mobile);
		user.setQq(qq);
		user.setMail(mail);
		user.setWeixinid(weixinid);
		user.setBirthplace(birthplace);
		user.setAddress(address);
		user.setReferee(referee);
        user.setIfsend(Integer.parseInt(ifsend));
        user.setCreatetime(createtime);

		user.setSendaddress(sendaddress);
		
		List<TUserScan> userScanlist=new ArrayList<>();
		TUserScan userScan = null;
//		String datatype=request.getParameter("datatype");
//		if(!"".equals(datatype)&&datatype!=null){
//			userScan.setType(Integer.parseInt(datatype));
//		}
		//毕业基本信息 >>>>>>>>>>>>>>>>>>>>>
		Map<String, TUserEducation> eduMap = new HashMap();
		TUserEducation education = null;
		String graduationtime=request.getParameter("graduationtime");
		String universitie=request.getParameter("universitie");
		String major=request.getParameter("major");
		String educationNum=request.getParameter("educationNum");
		String academicdegreeNum=request.getParameter("academicdegreeNum");
		if(graduationtime != null){
			education = new TUserEducation();
			education.setAcademicdegreeNum(academicdegreeNum);
		    education.setEducationNum(educationNum);
		    Long gtime;
		    try {
		    	gtime = format.parse(graduationtime).getTime();
		    	education.setGraduationtime(gtime);
		    } catch (ParseException e) {
		    }
		    education.setMajor(major);
		    education.setUniversitie(universitie);
		    eduMap.put("0", education);
		}
		String graduationtime1=request.getParameter("graduationtime1");
		String universitie1=request.getParameter("universitie1");
		String major1=request.getParameter("major1");
		String educationNum1=request.getParameter("educationNum1");
		String academicdegreeNum1=request.getParameter("academicdegreeNum1");
		if(graduationtime1 != null){
			education = new TUserEducation();
			education.setAcademicdegreeNum(academicdegreeNum1);
		    education.setEducationNum(educationNum1);
		    Long gtime;
		    try {
		    	gtime = format.parse(graduationtime1).getTime();
		    	education.setGraduationtime(gtime);
		    } catch (ParseException e) {
		    }
		    education.setMajor(major1);
		    education.setUniversitie(universitie1);
		    eduMap.put("1", education);
		}
		String graduationtime2=request.getParameter("graduationtime2");
		String universitie2=request.getParameter("universitie2");
		String major2=request.getParameter("major2");
		String educationNum2=request.getParameter("educationNum2");
		String academicdegreeNum2=request.getParameter("academicdegreeNum2");
		if(graduationtime2 != null){
			education = new TUserEducation();
			education.setAcademicdegreeNum(academicdegreeNum2);
		    education.setEducationNum(educationNum2);
		    Long gtime;
		    try {
		    	gtime = format.parse(graduationtime2).getTime();
		    	education.setGraduationtime(gtime);
		    } catch (ParseException e) {
		    }
		    education.setMajor(major2);
		    education.setUniversitie(universitie2);
		    eduMap.put("2", education);
		}
		String graduationtime3=request.getParameter("graduationtime3");
		String universitie3=request.getParameter("universitie3");
		String major3=request.getParameter("major3");
		String educationNum3=request.getParameter("educationNum3");
		String academicdegreeNum3=request.getParameter("academicdegreeNum3");
		if(graduationtime3 != null){
			education = new TUserEducation();
			education.setAcademicdegreeNum(academicdegreeNum3);
		    education.setEducationNum(educationNum3);
		    Long gtime;
		    try {
		    	gtime = format.parse(graduationtime3).getTime();
		    	education.setGraduationtime(gtime);
		    } catch (ParseException e) {
		    }
		    education.setMajor(major3);
		    education.setUniversitie(universitie3);
		    eduMap.put("3", education);
		}
		//毕业基本信息end >>>>>>>>>>>>>>>>>>>>>
		
		
		
		TUserEmergencycontact userEmergencycontact=new TUserEmergencycontact();
		String rname=request.getParameter("rname");
		String relationship=request.getParameter("relationship");
		String rmobile=request.getParameter("rmobile");
		String age=request.getParameter("age");
		String positions=request.getParameter("positions");
		if(!"".equals(age)){
			userEmergencycontact.setAge(Integer.parseInt(age));
		}
		userEmergencycontact.setMobile(rmobile);
		userEmergencycontact.setName(rname);
		userEmergencycontact.setPositions(positions);
		userEmergencycontact.setRelationship(relationship);
		
//		List<TUserWorkexperience> userwordlist = new ArrayList<>();
		
		TUserWorkexperience userWorkexperience=new TUserWorkexperience();
		String start_time=request.getParameter("starttime");
		String end_time=request.getParameter("endtime");
		String unitname=request.getParameter("unitname");
		String wpositions=request.getParameter("wpositions");
		String salaryStr=request.getParameter("salary");
		Double salary=0.00;
		if(!"".equals(salaryStr)){
			salary=Double.valueOf(salaryStr);
		}
		
		String witness=request.getParameter("witness");
		String wmobile=request.getParameter("wmobile");
		Long endtime;
	    Long starttime;
		try {
			endtime = formatym.parse(end_time).getTime();
			starttime = formatym.parse(start_time).getTime();
			userWorkexperience.setStarttime(starttime);
			userWorkexperience.setEndtime(endtime);
		} catch (ParseException e) {
		}
		userWorkexperience.setMobile(wmobile);
		userWorkexperience.setPositions(wpositions);
		userWorkexperience.setSalary(salary);
		userWorkexperience.setUnitname(unitname);
		userWorkexperience.setWitness(witness);
		
		TUserPrivate userPrivate =new TUserPrivate();
		String bankname=request.getParameter("bankname");
		String bankcardno=request.getParameter("bankcardno");
		String securityno=request.getParameter("securityno");
		String accumulationno=request.getParameter("accumulationno");
		userPrivate.setAccumulationno(accumulationno);
		userPrivate.setBankcardno(bankcardno);
		userPrivate.setBankname(bankname);
		userPrivate.setSecurityno(securityno);
		TOrganization ion=organizationService.getTOrganizationByid(organizationid);
		ion.setNumber(ion.getNumber()+1);
		int fal=userService.insertTUser(user);
		//生成镜像表
		userCopyService.insertTUserByUser(user);
		organizationService.updateTOrganization(ion);
//		System.out.println(sendaddress);
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
	    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
	    // 检查form中是否有enctype="multipart/form-data"
	    if (multipartResolver.isMultipart(request)) {
	      // 将request变成多部分request
	      MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
	      // 获取multiRequest 中所有的文件名
	      Iterator<String> iter = multiRequest.getFileNames();
	      Long uploadtime = new Date().getTime();
	      while (iter.hasNext()) {
	        // 一次遍历所有文件
	        MultipartFile file = multiRequest.getFile(iter.next());
	        if (!file.isEmpty()) {
	          // 服务端保存文件的路径
	          String path = "";
	          // 数据库保存路径
	          String sqlpath = "";
	          String subpath = "/"+user.getId()+"/"+UUID.randomUUID().toString().replace("-", "")+file.getOriginalFilename();
	          if("datafile1".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(1);
	        	  path = ServiceConfig.fileUploadPath+"/employee"+subpath;
	        	  sqlpath = "upload"+"/employee"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile2".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(2);
	        	  path = ServiceConfig.fileUploadPath+"/resume"+subpath;
	        	  sqlpath = "upload"+"/resume"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile3".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(3);
	        	  path = ServiceConfig.fileUploadPath+"/examination"+subpath;
	        	  sqlpath = "upload"+"/examination"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile4".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(4);
	        	  path = ServiceConfig.fileUploadPath+"/id"+subpath;
	        	  sqlpath = "upload"+"/id"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile5".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(5);
	        	  path = ServiceConfig.fileUploadPath+"/education"+subpath;
	        	  sqlpath = "upload"+"/education"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile6".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(6);
	        	  path = ServiceConfig.fileUploadPath+"/contract"+subpath;
	        	  sqlpath = "upload"+"/contract"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile7".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(7);
	        	  path = ServiceConfig.fileUploadPath+"/upLeavingCertificate"+subpath;
	        	  sqlpath = "upload"+"/upLeavingCertificate"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile8".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(8);
	        	  path = ServiceConfig.fileUploadPath+"/leavingCertificateApproval"+subpath;
	        	  sqlpath = "upload"+"/leavingCertificateApproval"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile9".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(9);
	        	  path = ServiceConfig.fileUploadPath+"/leavingCertificate"+subpath;
	        	  sqlpath = "upload"+"/leavingCertificate"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile10".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(10);
	        	  path = ServiceConfig.fileUploadPath+"/interviewRecords"+subpath;
	        	  sqlpath = "upload"+"/interviewRecords"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile11".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(11);
	        	  path = ServiceConfig.fileUploadPath+"/bankCard"+subpath;
	        	  sqlpath = "upload"+"/bankCard"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile12".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(12);
	        	  path = ServiceConfig.fileUploadPath+"/idBack"+subpath;
	        	  sqlpath = "upload"+"/idBack"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("bankfile".equals(file.getName())){
	        	  path = ServiceConfig.fileUploadPath+"/bankpath"+subpath;
	        	  sqlpath = "upload"+"/bankpath"+subpath;
	        	  userPrivate.setBankpath(sqlpath);
	        	  userPrivate.setUploadtime(uploadtime);
	          }else if("educationfile".equals(file.getName())){
	        	  if(eduMap.get("0") != null){
	        		  path = ServiceConfig.fileUploadPath+"/education"+subpath;
	        		  sqlpath = "upload"+"/education"+subpath;
	        		  eduMap.get("0").setEducationPath(sqlpath);
	        		  eduMap.get("0").setEducationUploadtime(uploadtime);
	        	  }
	          }else if("educationfile1".equals(file.getName())){
	        	  if(eduMap.get("1") != null){
	        		  path = ServiceConfig.fileUploadPath+"/education"+subpath;
	        		  sqlpath = "upload"+"/education"+subpath;
	        		  eduMap.get("1").setEducationPath(sqlpath);
	        		  eduMap.get("1").setEducationUploadtime(uploadtime);
	        	  }
	          }else if("educationfile2".equals(file.getName())){
	        	  if(eduMap.get("2") != null){
	        		  path = ServiceConfig.fileUploadPath+"/education"+subpath;
	        		  sqlpath = "upload"+"/education"+subpath;
	        		  eduMap.get("2").setEducationPath(sqlpath);
	        		  eduMap.get("2").setEducationUploadtime(uploadtime);
	        	  }
	          }else if("educationfile3".equals(file.getName())){
	        	  if(eduMap.get("3") != null){
	        		  path = ServiceConfig.fileUploadPath+"/education"+subpath;
	        		  sqlpath = "upload"+"/education"+subpath;
	        		  eduMap.get("3").setEducationPath(sqlpath);
	        		  eduMap.get("3").setEducationUploadtime(uploadtime);
	        	  }
	          }else if("academicdegreefile".equals(file.getName())){
	        	  if(eduMap.get("0") != null){
	        		  path = ServiceConfig.fileUploadPath+"/academicdegree"+subpath;
	        		  sqlpath = "upload"+"/academicdegree"+subpath;
	        		  eduMap.get("0").setAcademicdegreePath(sqlpath);
	        		  eduMap.get("0").setAcademicdegreeUploadtime(uploadtime);
	        	  }
	          }else if("academicdegreefile1".equals(file.getName())){
	        	  if(eduMap.get("1") != null){
	        		  path = ServiceConfig.fileUploadPath+"/academicdegree"+subpath;
	        		  sqlpath = "upload"+"/academicdegree"+subpath;
	        		  eduMap.get("1").setAcademicdegreePath(sqlpath);
	        		  eduMap.get("1").setAcademicdegreeUploadtime(uploadtime);
	        	  }
	          }else if("academicdegreefile2".equals(file.getName())){
	        	  if(eduMap.get("2") != null){
	        		  path = ServiceConfig.fileUploadPath+"/academicdegree"+subpath;
	        		  sqlpath = "upload"+"/academicdegree"+subpath;
	        		  eduMap.get("2").setAcademicdegreePath(sqlpath);
	        		  eduMap.get("2").setAcademicdegreeUploadtime(uploadtime);
	        	  }
	          }else if("academicdegreefile3".equals(file.getName())){
	        	  if(eduMap.get("3") != null){
	        		  path = ServiceConfig.fileUploadPath+"/academicdegree"+subpath;
	        		  sqlpath = "upload"+"/academicdegree"+subpath;
	        		  eduMap.get("3").setAcademicdegreePath(sqlpath);
	        		  eduMap.get("3").setAcademicdegreeUploadtime(uploadtime);
	        	  }
	          }
	          File uploadFile = new File(path);
	          if (!uploadFile.exists()) {
	            // 当保存文件的目录不存在则创建
	            uploadFile.mkdirs();
	          }
	          
//	          System.out.println(path);
	          //System.out.println(file.getOriginalFilename()+"++++++++++++++++++++");
	          // 上传
	          file.transferTo(new File(uploadFile.getAbsolutePath()));
	          if("datafile4".equals(file.getName())){
	        	  //身份证识别
	        	  Map<String, Object> map = IdIdentificationApiUtil.getIdImageData(ServiceConfig.fileUploadPath+"/id"+subpath);
	        	  if((int)map.get("idcode") == 0){
	        		  String num = (String)map.get("num");
	            		if(num != null || !num.trim().equals("")){
	            			//判断身份证是否可以注册
	            			if(!userService.userIdcardIsExist((String)map.get("num"), user.getOrganizationId()+"",null)){
	            				SimpleDateFormat idmdf = new SimpleDateFormat("yyyyMMdd"); 
	            				TUser user2 = new TUser();
	            				user2.setBirthplace((String)map.get("address"));//地址
	            				try {
	            					user2.setDatebirth(idmdf.parse((String)map.get("birth")).getTime());//出生日期
	            				} catch (Exception e) {
	            				}
	            				user2.setName((String)map.get("name"));//姓名
	            				user2.setNation((String)map.get("nationality"));//民族
	            				user2.setIdcard((String)map.get("num"));//身份证号码
	            				if(map.get("sex").equals("男")){
	            					user2.setSex(1);
	            				}else{
	            					user2.setSex(2);
	            				}
	            				//更新用户表
	            				user2.setId(user.getId());
	            				userService.updateTUser(user2);
	            				//修改镜像
	            				userCopyService.updateTUserByUser(user2);
	            			}
	            		}
	        	  }
	          }else if ("bankfile".equals(file.getName())) {
				//银行卡识别
	        	  Map<String, Object> map3 = BankCardPicApiUtil.getBankData(ServiceConfig.fileUploadPath+"/bankpath"+subpath);
	        	  if((int)map3.get("code") == 0){
	        		  	userPrivate.setBankcardno((String)map3.get("cardnumber"));
					}
			}
	        }
	      }
	    }
	    if(fal>0){
//			System.out.println("添加用户成功");
			//创建其他数据表
//			userEducation.setUserId(user.getId());
	    	
	    	//默认添加一条薪资信息
	    	TUserPay userPay = new TUserPay();
	    	userPay.setUserId(user.getId());
	    	userPay.setStatus(1);
	    	userPay.setBasesalary(1200);
	    	userPay.setType(1);
	    	userPay.setSalary(60);
	    	userPay.setDays(22);
	    	userPay.setBasicStatus(2);
	    	userPayService.insertTUserPay(userPay);
			userEmergencycontact.setUserId(user.getId());
			userWorkexperience.setUserId(user.getId());
			userPrivate.setUserId(user.getId());
			for (TUserScan tUserScan : userScanlist) {
				tUserScan.setUserId(user.getId());
				userScanService.insertTUserScan(tUserScan);
				userScanCopyService.insertTUserScanByUserScan(tUserScan);
			}
			Iterator mapiter = eduMap.entrySet().iterator();
	        while (mapiter.hasNext()) {
	        Map.Entry entry = (Map.Entry) mapiter.next();
	        TUserEducation userEduca = (TUserEducation) entry.getValue();
	        if(userEduca.getGraduationtime() == null && (userEduca.getUniversitie() == null || userEduca.getUniversitie().equals("")) 
	        	&& (userEduca.getMajor() == null || userEduca.getMajor().equals("")) && (userEduca.getEducationNum() == null || userEduca.getEducationNum().equals("")) 
	        	&& (userEduca.getAcademicdegreeNum() == null || userEduca.getAcademicdegreeNum().equals("")) && (userEduca.getEducationPath() == null || userEduca.getEducationPath().equals(""))
	        	&& (userEduca.getAcademicdegreePath() == null || userEduca.getAcademicdegreePath().equals(""))){
	        }else{
	        	userEduca.setUserId(user.getId());
	        	userEducationService.insertTUserEducation(userEduca);
	        	userEducationCopyService.insertTUserEducationByMain(userEduca);
	        }
	        }
	        if((userEmergencycontact.getName() == null || userEmergencycontact.getName().equals("")) 
	        		&& (userEmergencycontact.getRelationship() == null || userEmergencycontact.getRelationship().equals(""))
	        		&& (userEmergencycontact.getMobile() == null || userEmergencycontact.getMobile().equals("")) 
	        		&& userEmergencycontact.getAge() == null && (userEmergencycontact.getPositions() == null || userEmergencycontact.getPositions().equals(""))){
	        }else {
	        	userEmergencycontactService.insertTUserEmergencycontact(userEmergencycontact);
	        	userEmergencycontactCopyService.insertTUserEmergencycontactByMain(userEmergencycontact);
			}
	        if(userWorkexperience.getStarttime() == null && userWorkexperience.getEndtime() == null 
	        		&& (userWorkexperience.getUnitname() == null || userWorkexperience.getUnitname().equals("")) 
	        		&& (userWorkexperience.getPositions() == null || userWorkexperience.getPositions().equals("")) 
	        		&& userWorkexperience.getSalary() == 0.0 && (userWorkexperience.getWitness() == null || userWorkexperience.getWitness().equals("")) 
	        		&& (userWorkexperience.getMobile() == null || userWorkexperience.getMobile().equals(""))){
	        }else {
	        	userWorkexperienceService.insertTUserWorkexperience(userWorkexperience);
	        	userWorkexperienceCopyService.insertTUserWorkexperienceByMain(userWorkexperience);
			}
	        if((userPrivate.getAccumulationno() == null || userPrivate.getAccumulationno().equals("")) 
	        		&& (userPrivate.getSecurityno() == null || userPrivate.getSecurityno().equals("")) 
	        		&& (userPrivate.getBankcardno() == null || userPrivate.getBankcardno().equals("")) 
	        		&& (userPrivate.getBankname() == null || userPrivate.getBankname().equals("")) 
	        		&& (userPrivate.getBankpath() == null || userPrivate.getBankpath().equals(""))){
	        }else {
	        	userPrivateService.insertTUserPrivate(userPrivate);
	        	userPrivateCopyService.insertTUserPrivateByMain(userPrivate);
			}
			//request.getSession().setAttribute("userid", user.getId());
			img="ok";
//			System.out.println("添加成功");
		}else{
			img="no";
		}
		return img;
		
	}
	//修改用户信息
	@RequestMapping(value ="/update",method = RequestMethod.POST)
	@ResponseBody
	public String update(MultipartFile mfile,
            HttpServletRequest request,HttpServletResponse response) throws IOException{
		String name = request.getParameter("name");
		String sex = request.getParameter("sex");
		String datebirth = request.getParameter("datebirth");
		Long date_birth = null;
        if(!"".equals(datebirth) && datebirth!=null){
            try {
                 date_birth=format.parse(datebirth).getTime();
            } catch (ParseException e1) {
                // TODO 自动生成的 catch 块
                e1.printStackTrace();
            }
        }

		String origin = request.getParameter("origin");
		String politicalstatus = request.getParameter("politicalstatus");
		String[] lang =request.getParameterValues("language");
		
		String language_="";
		if(lang != null){
			for (int i = 0; i < lang.length; i++) {
				if(i==0){
					language_ = lang[i];
				}else{
					language_ += "," + lang[i];
				}
			}
		}
		 
		String speciality = request.getParameter("speciality");
		String highesteducation = request.getParameter("highesteducation");
		String professional = request.getParameter("professional");
		String idcard = request.getParameter("idcard");
		String maritalstatus = request.getParameter("maritalstatus");
		int maritalstatus_=0;
        if(maritalstatus!=""&&maritalstatus!=null){
            maritalstatus_=Integer.parseInt(maritalstatus);
        }
        String nation =request.getParameter("nation");

		String height = request.getParameter("height");
		String weight = request.getParameter("weight");
		String vision = request.getParameter("vision");
		String mobile = request.getParameter("mobile");
		String qq = request.getParameter("qq");
		String mail = request.getParameter("mail");
		String weixinid = request.getParameter("weixinid");
		String birthplace = request.getParameter("birthplace");
		String address = request.getParameter("address");
		String referee = request.getParameter("referee");
		String ifsend = request.getParameter("ifsend");
		String sendaddress = request.getParameter("sendaddress");
		String img="";
		String userid=request.getParameter("userid");
        String jobnumber=request.getParameter("jobnumber");
        Long modifytime=new Date().getTime();

		//查询数据by id
		TUser user=userService.selectTUserId(userid);
		//判断手机号码是否可以注册
		if(mobile != null && !mobile.equals("")){
			if(userService.userMobileIsExist(mobile,user.getOrganizationId()+"",userid)){
				return "mobileExist";
			}
		}
		if(idcard != null && !idcard.equals("")){
			//判断身份证是否可以注册
			if(userService.userIdcardIsExist(idcard, user.getOrganizationId()+"",userid)){
				return "idcardExist";
			}
		}
		user.setName(name);
        user.setJobnumber(jobnumber);
        user.setNation(nation);
        user.setLoginname(mobile);

		user.setSex(Integer.parseInt(sex));
		user.setDatebirth(date_birth);
		user.setOrigin(origin);
		user.setPoliticalstatus(politicalstatus);
		user.setLanguage(language_);
		user.setSpeciality(speciality);
		user.setHighesteducation(highesteducation);
		user.setProfessional(professional);
		user.setIdcard(idcard);
		user.setMaritalstatus(maritalstatus_);
		user.setHeight(height);
		user.setWeight(weight);
		user.setVision(vision);
		user.setMobile(mobile);
		user.setQq(qq);
		user.setMail(mail);
		user.setWeixinid(weixinid);
		user.setBirthplace(birthplace);
		user.setAddress(address);
		user.setReferee(referee);
        user.setIfsend(Integer.parseInt(ifsend));
        user.setModifytime(modifytime);

		user.setSendaddress(sendaddress);
		
		List<TUserScan> userScanlist=new ArrayList<>();
		TUserScan userScan = null;
//		String datatype=request.getParameter("datatype");
		//保存用户修改或者增加的学历信息
		Map<String, TUserEducation> educMap = new HashMap<>();
		//获取已有的学历信息id
		String[] educids = request.getParameterValues("educid");
		if(educids != null){
			for (String educid : educids) {
				TUserEducation education = new TUserEducation();
				educMap.put(educid, education);
			}
		}
		//获取修改的学历证书
		if(educids != null){
			Enumeration enu = request.getParameterNames();
			while (enu.hasMoreElements()) {
				String parameterName = (String) enu.nextElement();
				if(parameterName.indexOf("graduationtime") != -1){
					String educid = parameterName.split("graduationtime")[1];
					String graduationtime = request.getParameter(parameterName);
					Long gtime;
					try {
						gtime = format.parse(graduationtime).getTime();
						educMap.get(educid).setGraduationtime(gtime);
					} catch (ParseException e) {
					}
				}else if(parameterName.indexOf("universitie") != -1 && parameterName.indexOf("-") == -1){
					String educid = parameterName.split("universitie")[1];
					String universitie = request.getParameter(parameterName);
					educMap.get(educid).setUniversitie(universitie);
				}else if(parameterName.indexOf("major") != -1 && parameterName.indexOf("-") == -1){
					String educid = parameterName.split("major")[1];
					String major = request.getParameter(parameterName);
					educMap.get(educid).setMajor(major);
				}else if(parameterName.indexOf("educationNum") != -1 && parameterName.indexOf("-") == -1){
					String educid = parameterName.split("educationNum")[1];
					String educationNum = request.getParameter(parameterName);
					educMap.get(educid).setEducationNum(educationNum);
				}
				else if(parameterName.indexOf("academicdegreeNum") != -1 && parameterName.indexOf("-") == -1){
					String educid = parameterName.split("academicdegreeNum")[1];
					String academicdegreeNum = request.getParameter(parameterName);
					educMap.get(educid).setAcademicdegreeNum(academicdegreeNum);
				}
			}
		}
		TUserEducation education = null;
		//需要新增的学历信息
		String graduationtime1=request.getParameter("graduationtime-1");
		String universitie1=request.getParameter("universitie-1");
		String major1=request.getParameter("major-1");
		String educationNum1=request.getParameter("educationNum-1");
		String academicdegreeNum1=request.getParameter("academicdegreeNum-1");
		if(graduationtime1 != null){
			education = new TUserEducation();
			education.setAcademicdegreeNum(academicdegreeNum1);
		    education.setEducationNum(educationNum1);
		    Long gtime;
		    try {
		    	gtime = format.parse(graduationtime1).getTime();
		    	education.setGraduationtime(gtime);
		    } catch (ParseException e) {
		    }
		    education.setUserId(Integer.parseInt(userid));
		    education.setMajor(major1);
		    education.setUniversitie(universitie1);
		    educMap.put("-1", education);
		}
		String graduationtime2=request.getParameter("graduationtime-2");
		String universitie2=request.getParameter("universitie-2");
		String major2=request.getParameter("major-2");
		String educationNum2=request.getParameter("educationNum-2");
		String academicdegreeNum2=request.getParameter("academicdegreeNum-2");
		if(graduationtime2 != null){
			education = new TUserEducation();
			education.setUserId(Integer.parseInt(userid));
			education.setAcademicdegreeNum(academicdegreeNum2);
		    education.setEducationNum(educationNum2);
		    Long gtime;
		    try {
		    	gtime = format.parse(graduationtime2).getTime();
		    	education.setGraduationtime(gtime);
		    } catch (ParseException e) {
		    }
		    education.setMajor(major2);
		    education.setUniversitie(universitie2);
		    educMap.put("-2", education);
		}
		String graduationtime3=request.getParameter("graduationtime-3");
		String universitie3=request.getParameter("universitie-3");
		String major3=request.getParameter("major-3");
		String educationNum3=request.getParameter("educationNum-3");
		String academicdegreeNum3=request.getParameter("academicdegreeNum-3");
		if(graduationtime3 != null){
			education = new TUserEducation();
			education.setUserId(Integer.parseInt(userid));
			education.setAcademicdegreeNum(academicdegreeNum3);
		    education.setEducationNum(educationNum3);
		    Long gtime;
		    try {
		    	gtime = format.parse(graduationtime3).getTime();
		    	education.setGraduationtime(gtime);
		    } catch (ParseException e) {
		    }
		    education.setMajor(major3);
		    education.setUniversitie(universitie3);
		    educMap.put("-3", education);
		}
		
		TUserEmergencycontact userEmergencycontact=userEmergencycontactService.selectUserEmergencycontactByUid(userid);
		if(userEmergencycontact != null){
			String rname=request.getParameter("rname");
			String relationship=request.getParameter("relationship");
			String rmobile=request.getParameter("rmobile");
			String age=request.getParameter("age");
			String positions=request.getParameter("positions");
			if(!"".equals(age)){
				userEmergencycontact.setAge(Integer.parseInt(age));
			}
			
			userEmergencycontact.setMobile(rmobile);
			userEmergencycontact.setName(rname);
			userEmergencycontact.setPositions(positions);
			userEmergencycontact.setRelationship(relationship);
		}
		
		TUserWorkexperience userWorkexperience=userWorkexperienceService.selectUserWorkexperienceByUid(userid);
		if(userWorkexperience != null){
			String start_time=request.getParameter("starttime");
			String end_time=request.getParameter("endtime");
			String unitname=request.getParameter("unitname");
			String wpositions=request.getParameter("wpositions");
			String salaryStr=request.getParameter("salary");
			Double salary=0.00;
			if(!"".equals(salaryStr)){
				salary=Double.valueOf(salaryStr);
			}
			
			String witness=request.getParameter("witness");
			String wmobile=request.getParameter("wmobile");
			Long endtime;
			Long starttime;
			try {
				endtime = formatym.parse(end_time).getTime();
				starttime = formatym.parse(start_time).getTime();
				userWorkexperience.setStarttime(starttime);
				userWorkexperience.setEndtime(endtime);
			} catch (ParseException e) {
			}
			userWorkexperience.setMobile(wmobile);
			userWorkexperience.setPositions(wpositions);
			userWorkexperience.setSalary(salary);
			userWorkexperience.setUnitname(unitname);
			userWorkexperience.setWitness(witness);
		}
		TUserPrivate userPrivate =userPrivateService.selectUserPrivateByUid(userid);
		if(userPrivate != null){
			String bankname=request.getParameter("bankname");
			String bankcardno=request.getParameter("bankcardno");
			String securityno=request.getParameter("securityno");
			String accumulationno=request.getParameter("accumulationno");
			userPrivate.setAccumulationno(accumulationno);
			userPrivate.setBankcardno(bankcardno);
			userPrivate.setBankname(bankname);
			userPrivate.setSecurityno(securityno);
		}
		
//		System.out.println(sendaddress);
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
	    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
	    // 检查form中是否有enctype="multipart/form-data"
	    if (multipartResolver.isMultipart(request)) {
	      // 将request变成多部分request
	      MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
	      // 获取multiRequest 中所有的文件名
	      Iterator<String> iter = multiRequest.getFileNames();
	      Long uploadtime = new Date().getTime();
	      while (iter.hasNext()) {
	        // 一次遍历所有文件
	        MultipartFile file = multiRequest.getFile(iter.next());
	        if (!file.isEmpty()) {
        	// 服务端保存文件的路径
	          String path = "";
	          // 数据库保存路径
	          String sqlpath = "";
	          String subpath = "/"+user.getId()+"/"+UUID.randomUUID().toString().replace("-", "")+file.getOriginalFilename();
	          if("datafile1".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(1);
	        	  path = ServiceConfig.fileUploadPath+"/employee"+subpath;
	        	  sqlpath = "upload"+"/employee"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile2".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(2);
	        	  path = ServiceConfig.fileUploadPath+"/resume"+subpath;
	        	  sqlpath = "upload"+"/resume"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile3".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(3);
	        	  path = ServiceConfig.fileUploadPath+"/examination"+subpath;
	        	  sqlpath = "upload"+"/examination"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile4".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(4);
	        	  path = ServiceConfig.fileUploadPath+"/id"+subpath;
	        	  sqlpath = "upload"+"/id"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile5".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(5);
	        	  path = ServiceConfig.fileUploadPath+"/education"+subpath;
	        	  sqlpath = "upload"+"/education"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile6".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(6);
	        	  path = ServiceConfig.fileUploadPath+"/contract"+subpath;
	        	  sqlpath = "upload"+"/contract"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile7".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(7);
	        	  path = ServiceConfig.fileUploadPath+"/upLeavingCertificate"+subpath;
	        	  sqlpath = "upload"+"/upLeavingCertificate"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile8".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(8);
	        	  path = ServiceConfig.fileUploadPath+"/leavingCertificateApproval"+subpath;
	        	  sqlpath = "upload"+"/leavingCertificateApproval"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile9".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(9);
	        	  path = ServiceConfig.fileUploadPath+"/leavingCertificate"+subpath;
	        	  sqlpath = "upload"+"/leavingCertificate"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile10".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(10);
	        	  path = ServiceConfig.fileUploadPath+"/interviewRecords"+subpath;
	        	  sqlpath = "upload"+"/interviewRecords"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile11".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(11);
	        	  path = ServiceConfig.fileUploadPath+"/bankCard"+subpath;
	        	  sqlpath = "upload"+"/bankCard"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if("datafile12".equals(file.getName())){
	        	  userScan = new TUserScan();
	        	  userScan.setType(12);
	        	  path = ServiceConfig.fileUploadPath+"/idBack"+subpath;
	        	  sqlpath = "upload"+"/idBack"+subpath;
	        	  userScan.setPath(sqlpath);
	        	  userScan.setUploadtime(uploadtime);
	        	  userScanlist.add(userScan);
	          }else if(file.getName().indexOf("educationfile") != -1){
	        	  String educid = file.getName().split("educationfile")[1];
	        	  path = ServiceConfig.fileUploadPath+"/education"+subpath;
	        	  sqlpath = "upload"+"/education"+subpath;
	        	  educMap.get(educid).setEducationUploadtime(uploadtime);
	        	  educMap.get(educid).setEducationPath(sqlpath);
	          }else if(file.getName().indexOf("academicdegreefile") != -1){
	        	  String educid = file.getName().split("academicdegreefile")[1];
	        	  path = ServiceConfig.fileUploadPath+"/academicdegree"+subpath;
	        	  sqlpath = "upload"+"/academicdegree"+subpath;
	        	  educMap.get(educid).setAcademicdegreeUploadtime(uploadtime);
	        	  educMap.get(educid).setAcademicdegreePath(sqlpath);
	          }else if("bankfile".equals(file.getName())){
	        	  path = ServiceConfig.fileUploadPath+"/bankpath"+subpath;
	        	  sqlpath = "upload"+"/bankpath"+subpath;
	        	  userPrivate.setUploadtime(uploadtime);
	        	  userPrivate.setBankpath(sqlpath);
	          }
	          File uploadFile = new File(path);
	          if (!uploadFile.exists()) {
	            // 当保存文件的目录不存在则创建
	            uploadFile.mkdirs();
	          }
//	          System.out.println(path);
	          //System.out.println(file.getOriginalFilename()+"++++++++++++++++++++");
	          // 上传
	          file.transferTo(new File(uploadFile.getAbsolutePath()));
	          if("datafile4".equals(file.getName())){
	        	  //身份证识别
	        	  Map<String, Object> map = IdIdentificationApiUtil.getIdImageData(ServiceConfig.fileUploadPath+"/id"+subpath);
	        	  if((int)map.get("idcode") == 0){
	        		  String num = (String)map.get("num");
	            		if(num != null || !num.trim().equals("")){
	            			//判断身份证是否可以注册
	            			if(!userService.userIdcardIsExist((String)map.get("num"), user.getOrganizationId()+"",userid)){
	            				SimpleDateFormat idmdf = new SimpleDateFormat("yyyyMMdd"); 
	            				user.setBirthplace((String)map.get("address"));//地址
	            				try {
	            					user.setDatebirth(idmdf.parse((String)map.get("birth")).getTime());//出生日期
	            				} catch (Exception e) {
	            				}
	            				user.setName((String)map.get("name"));//姓名
	            				user.setNation((String)map.get("nationality"));//民族
	            				user.setIdcard((String)map.get("num"));//身份证号码
	            				if(map.get("sex").equals("男")){
	            					user.setSex(1);
	            				}else{
	            					user.setSex(2);
	            				}
	            			}
	            		}
	        	  }
	          }else if ("bankfile".equals(file.getName())) {
				//银行卡识别
	        	  Map<String, Object> map3 = BankCardPicApiUtil.getBankData(ServiceConfig.fileUploadPath+"/bankpath"+subpath);
	        	  if((int)map3.get("code") == 0){
	        		  	userPrivate.setBankcardno((String)map3.get("cardnumber"));
					}
			}
	          img=file.getOriginalFilename();
	          
	        }
	      }
	    }
	    //修改数据
        int f=userService.updateTUser(user);
        userCopyService.updateTUserByUser(user);
        if(f>0){
        	for (TUserScan tUserScan : userScanlist) {
				tUserScan.setUserId(user.getId());
				int isUpdate = userScanService.updateUserScanByUseridAndType(tUserScan);
				userScanCopyService.updateUserScanByUseridAndTypeByUserScan(tUserScan);
				if(isUpdate == 0){
					userScanService.insertTUserScan(tUserScan);
					userScanCopyService.insertTUserScanByUserScan(tUserScan);
				}
			}
        	Iterator mapiter = educMap.entrySet().iterator();
	        while (mapiter.hasNext()) {
		        Map.Entry entry = (Map.Entry) mapiter.next();
		        String educid = (String) entry.getKey();
		        TUserEducation userEduca = (TUserEducation) entry.getValue();
		        if(educid.equals("-1") || educid.equals("-2") || educid.equals("-3")){
		        	userEducationService.insertTUserEducation(userEduca);
		        	userEducationCopyService.insertTUserEducationByMain(userEduca);
		        }else{
		        	userEduca.setId(Integer.parseInt(educid));
		        	userEducationService.updateUserEducation(userEduca);
		        	userEducationCopyService.updateUserEducationByMain(userEduca);
		        }
	        }
	        if(userEmergencycontact != null){
	        	int m=userEmergencycontactService.updateUserEmergencycontact(userEmergencycontact);
	        	userEmergencycontactCopyService.updateUserEmergencycontactByMain(userEmergencycontact);
	        }
	        if(userPrivate != null){
	        	int mm=userPrivateService.updateUserPrivate(userPrivate);
	        	userPrivateCopyService.updateUserPrivateByMain(userPrivate);
	        }
	        if(userWorkexperience != null){
	        	int ss=userWorkexperienceService.updateUserWorkexperience(userWorkexperience);
	        	userWorkexperienceCopyService.updateUserWorkexperienceByMain(userWorkexperience);
	        }
	        //资料审核状态还原
	        userService.updateExamineStatus(userid, "1");
            img="ok";
        }else{
            img="no";
        }

		return img;
	}
	/**
	 * 用户资料镜像是否被修改
	 * @param userid
	 * @return
	 */
//	public static boolean Comparison(TUser user,TUserBuffer userCopy){
//		boolean isUpdate = false;
//		if(!user.toString().equals(userCopy.toString())){
//			isUpdate = true;
//			return isUpdate;
//		}
//		//比较用户私密信息
//		TUserPrivate userPrivate = user.getUserPrivate();
//		TUserPrivateBuffer privateCopy = userCopy.getUserPrivate();
//		if(!userPrivate.toString().equals(privateCopy.toString())){
//			isUpdate = true;
//			return isUpdate;
//		}
//		//比较用户学历信息
//		List<TUserEducation> tUserEducations = user.getEducationlist();
//		List<TUserEducationBuffer> tUserEducationCopies = userCopy.getEducationlist();
//		if(tUserEducations.size() != tUserEducationCopies.size()){
//			isUpdate = true;
//			return isUpdate;
//		}
//		for (int i = 0; i < tUserEducations.size(); i++) {
//			if(!tUserEducations.get(i).toString().equals(tUserEducationCopies.get(i).toString())){
//				isUpdate = true;
//				return isUpdate;
//			}
//		}
//		//比较用户紧急联系人信息
//		List<TUserEmergencycontact> emergencycontacts = user.getUserEmergencycontactlist();
//		List<TUserEmergencycontactBuffer> emergencycontactCopies = userCopy.getUserEmergencycontactlist();
//		if(emergencycontacts.size() != emergencycontactCopies.size()){
//			isUpdate = true;
//			return isUpdate;
//		}
//		for (int i = 0; i < emergencycontacts.size(); i++) {
//			if(!emergencycontacts.get(i).toString().equals(emergencycontactCopies.get(i).toString())){
//				isUpdate = true;
//				return isUpdate;
//			}
//		}
//		//比较用户工作经历信息
//		List<TUserWorkexperience> userWorkexperiences = user.getUserWorkexperiencelist();
//		List<TUserWorkexperienceBuffer> tUserWorkexperienceCopies = userCopy.getUserWorkexperiencelist();
//		if(userWorkexperiences.size() != tUserWorkexperienceCopies.size()){
//			isUpdate= true;
//			return isUpdate;
//		}
//		for (int i = 0; i < userWorkexperiences.size(); i++) {
//			if(!userWorkexperiences.get(i).toString().equals(tUserWorkexperienceCopies.get(i).toString())){
//				isUpdate = true;
//				return isUpdate;
//			}
//		}
//		//比较用户附件信息
//		List<TUserScan> scans = user.getScanlist();
//		List<TUserScanBuffer> scanCopies = userCopy.getScanlist();
//		if(scans.size() != scanCopies.size()){
//			isUpdate = true;
//			return isUpdate;
//		}
//		for (int i = 0; i < scans.size(); i++) {
//			if(!scans.get(i).toString().equals(scanCopies.get(i).toString())){
//				isUpdate = true;
//				return isUpdate;
//			}
//		}
//		return isUpdate;
//	}
	/**
	 * 用户资料私密信息镜像是否被修改
	 * @param userid
	 * @return
	 */
	public static boolean ComparisonPrivate(TUserPrivate userPrivate,TUserPrivateBuffer privateCopy){
		boolean isUpdate = false;
		//比较用户私密信息
		if(!userPrivate.toString().equals(privateCopy.toString())){
			isUpdate = true;
			return isUpdate;
		}
		return isUpdate;
	}
	/**
	 * 用户资料学历信息镜像是否被修改
	 * @param userid
	 * @return
	 */
	public static boolean ComparisonEducations(List<TUserEducation> tUserEducations,List<TUserEducationBuffer> tUserEducationCopies){
		boolean isUpdate = false;
		//比较用户学历信息
		if(tUserEducations.size() != tUserEducationCopies.size()){
			isUpdate = true;
			return isUpdate;
		}
		for (int i = 0; i < tUserEducations.size(); i++) {
			if(!tUserEducations.get(i).toString().equals(tUserEducationCopies.get(i).toString())){
				isUpdate = true;
				return isUpdate;
			}
		}
		return isUpdate;
	}
	/**
	 * 用户资料紧急联系人信息镜像是否被修改
	 * @param userid
	 * @return
	 */
	public static boolean ComparisonEmergencycontact(List<TUserEmergencycontact> emergencycontacts,List<TUserEmergencycontactBuffer> emergencycontactCopies){
		boolean isUpdate = false;
		//比较用户紧急联系人信息
		if(emergencycontacts.size() != emergencycontactCopies.size()){
			isUpdate = true;
			return isUpdate;
		}
		for (int i = 0; i < emergencycontacts.size(); i++) {
			if(!emergencycontacts.get(i).toString().equals(emergencycontactCopies.get(i).toString())){
				isUpdate = true;
				return isUpdate;
			}
		}
		return isUpdate;
	}
	/**
	 * 用户工作经历信息镜像是否被修改
	 * @param userid
	 * @return
	 */
	public static boolean ComparisonWorkexperience(List<TUserWorkexperience> userWorkexperiences,List<TUserWorkexperienceBuffer> tUserWorkexperienceCopies){
		boolean isUpdate = false;
		//比较用户工作经历信息
		if(userWorkexperiences.size() != tUserWorkexperienceCopies.size()){
			isUpdate= true;
			return isUpdate;
		}
		for (int i = 0; i < userWorkexperiences.size(); i++) {
			if(!userWorkexperiences.get(i).toString().equals(tUserWorkexperienceCopies.get(i).toString())){
				isUpdate = true;
				return isUpdate;
			}
		}
		return isUpdate;
	}
	/**
	 * 用户附件信息镜像是否被修改
	 * @param userid
	 * @return
	 */
	public static boolean ComparisonScan(List<TUserScan> scans,List<TUserScanBuffer> scanCopies){
		boolean isUpdate = false;
		//比较用户附件信息
		if(scans.size() != scanCopies.size()){
			isUpdate = true;
			return isUpdate;
		}
		for (int i = 0; i < scans.size(); i++) {
			if(!scans.get(i).toString().equals(scanCopies.get(i).toString())){
				isUpdate = true;
				return isUpdate;
			}
		}
		return isUpdate;
	}
}

